package com.hqy.user.filter;

import com.hqy.user.util.GmallThreadLocalUtil;
import com.hqy.user.util.TokenUtil;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;

@Component
public class TokenFilter extends OncePerRequestFilter {

    private static final String AUTHORIZATION_HEADER = "Authorization";
    private static final String BEARER_PREFIX = "bearer ";
    private static final String USERNAME = "username";


    @Override
    protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, FilterChain filterChain) throws ServletException, IOException {
        String token = httpServletRequest.getHeader(AUTHORIZATION_HEADER).replace(BEARER_PREFIX, "");
        //从令牌的载荷中获取username
        Map<String, String> map = TokenUtil.dcodeToken(token);
        if (CollectionUtils.isEmpty(map)){
            return;
        }
        String username = map.get(USERNAME);
        GmallThreadLocalUtil.set(username);
        System.out.println("当前线程名称"+Thread.currentThread().getName());
        filterChain.doFilter(httpServletRequest, httpServletResponse);
    }
}
